<template>
  <div class="click-add">
    <canvas class="canvas"></canvas>
  </div>
</template>
<script setup>
import {onMounted} from 'vue';
import * as Three from 'three';
import util from '../util/index.js';

onMounted(() => {
  const canvas = document.getElementsByClassName('canvas')[0];
  let {width, height} = canvas.getBoundingClientRect();
  canvas.width = width;
  canvas.height = height;
  const gl = canvas.getContext('webgl');
  // 顶点着色器代码
  const vsSource = `
    attribute vec4 aPosition;
    attribute float aSize;
    void main(){
      gl_Position = aPosition;
      gl_PointSize = aSize;
    }`;
  // 片元着色器代码
  const fsSource = `
    precision mediump float;
    uniform vec4 uColor;
    // 循环执行main方法绘制每一个片元
    void main() {
      // 求当前片元距离中心点的距离，大于一半跳过，小于一半绘制
      float dist = distance(gl_PointCoord, vec2(0.5,0.5));
      if(dist < 0.5){
        gl_FragColor = uColor;
      }else{
        discard;
      }
    }`;
  // 装载着色器
  let program = util.initShaders(gl, vsSource, fsSource);
  // 开启片元颜色合成功能，设置片元合成方式
  gl.enable(gl.BLEND);
  gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  // 获取位置变量
  let aPosition = gl.getAttribLocation(program, 'aPosition');
  // 获取尺寸变量
  let aSize = gl.getAttribLocation(program, 'aSize');
  // 获取颜色变量
  let uColor = gl.getUniformLocation(program, 'uColor');
  // 保存要绘制的顶点信息
  let points = [];
  // 指定将要用来清理绘图区的颜色
  gl.clearColor(0.0, 0.0, 0.0, 0.0);
  // 刷底色
  gl.clear(gl.COLOR_BUFFER_BIT);
  canvas.addEventListener('click', e => {
    let {clientX, clientY} = e;
    let {left, top, width, height} = canvas.getBoundingClientRect();
    let [pointX, pointY] = [clientX - left, clientY - top];
    let [harfW, harfH] = [width / 2, height / 2];
    let [centerX, centerY] = [pointX - harfW, harfH - pointY];
    let [x, y] = [centerX / harfW, centerY / harfH];
    // 保存当前顶点信息
    points.push({
      x, y,
      size: Math.random() * 30 + 10,
      // color: [Math.random(), Math.random(), Math.random(), 1.0]
      color: [0.95, 0.85, 0.21, Math.random() * 0.7 + 0.3]
    });
    // 刷底色
    gl.clear(gl.COLOR_BUFFER_BIT);
    // 循环保存的顶点信息并绘制
    points.forEach(({x, y, size, color}) => {
      // 修改位置变量
      gl.vertexAttrib2f(aPosition, x, y);
      // 修改尺寸变量
      gl.vertexAttrib1f(aSize, size);
      // 修改颜色变量
      gl.uniform4f(uColor, ...color);
      // 绘制顶点
      gl.drawArrays(gl.POINTS, 0, 1);
    });
  });
});
</script>
<style lang="scss">
.click-add {
  .canvas {
    width: 100%;
    height: 100%;
    background-image: url("../assets/img/sky.jpg");
    background-size: cover;
    background-position: right bottom;
  }
}
</style>